package com.gfm.story.interceptor;

import com.gfm.story.entity.user.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * @BelongsProject: house-parent
 * @BelongsPackage: com.mooc.house.web.interceptor
 * @Author: Administrator
 * @CreateTime: 2019-04-24 15:29
 * @Description: 拦截器2：对于需要进行访问控制的资源进行判断处理。
 */
@Component
public class AuthActionInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //获取用户
        User user = UserContext.getUser();
        if (user == null) {//session中没有user信息
            String msg = URLEncoder.encode("请先登录","utf-8");//返回相应的错误信息
            String target = URLEncoder.encode(request.getRequestURL().toString(),"utf-8");//记录请求的路径
            if ("GET".equalsIgnoreCase(request.getMethod())) {//如果是get请求
                response.sendRedirect("/accounts/signin?errorMsg=" + msg + "&target="+target);//记录错误退出的路径
                return false;//修复bug,未登录要返回false
            }else {
                response.sendRedirect("/accounts/signin?errorMsg="+msg);//post请求，
                return false;//修复bug,未登录要返回false
            }
        }
        return true;
    }


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
